package com.xyhy.core.utils;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Editor;
import cn.hutool.core.util.ArrayUtil;

public class BeanUtils extends BeanUtil {

  public static <T, R> List<R> toBeans(Collection<T> srcList, Class<R> tgtClass) {
    if (Objects.isNull(srcList))
      return Collections.emptyList();
    return srcList.stream().map(x -> toBeanIgnoreNull(x, tgtClass)).collect(Collectors.toList());
  }

  public static <T> T toBeanIgnoreNull(Object source, Class<T> clazz) {
    return toBean(source, clazz, CopyOptions.create().setIgnoreNullValue(true));
  }

  public static Map<String, Object> beanToMap(Object bean, String... properties) {
    int mapSize = 16;
    Editor<String> keyEditor = null;
    if (ArrayUtil.isNotEmpty(properties)) {
      mapSize = properties.length;
      final Set<String> propertiesSet = CollUtil.set(false, properties);
      keyEditor = property -> propertiesSet.contains(property) ? property : null;
    }

    // 指明了要复制的属性 所以不忽略null值
    return beanToMap(bean, new HashMap<>(mapSize, 1), false, keyEditor);
  }

}
